<template>
  <div class="vwh100 login df_center">
    <div class="login-box">
      <header class="head">登录</header>
      <el-form :model="params" :rules="rules" ref="dataParams" label-width="80px" @keydown.enter.native="login">
        <el-form-item label="用户名：" prop="user_name">
          <el-input v-model="params.user_name"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="params.password" show-password></el-input>
        </el-form-item>
      </el-form>
      <div class="df_end"><el-button size="small" type="primary" @click="login">登录</el-button></div>
    </div>
  </div>
</template>

<script>
  // import HelloWorld from './components/HelloWorld.vue'
  import userManage from '@/api/user';
  import { mapGetters, mapActions } from 'vuex';

  export default {
    name: 'App',
    data() {
      return {
        params: {
          user_name: '',
          password: '',
        },
        rules: {
          user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
          password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        },
      };
    },
    components: {
      // HelloWorld
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo',
        token: 'token',
      }),
    },
    async mounted() {
      window.localStorage.removeItem('userinfo');
      window.localStorage.removeItem('ak');
    },
    methods: {
      ...mapActions({
        setToken: 'user/setToken',
        setUserInfo: 'user/setUserInfo',
      }),
      async login() {
        this.$refs.dataParams.validate((valid) => {
          if (valid) {
            userManage
              .login({
                user_name: this.params.user_name,
                password: this.$md5(this.params.user_name + '_' + this.$md5(this.params.password)),
              })
              .then((res) => {
                window.localStorage.setItem('ak', res.ak);
                window.localStorage.setItem('userinfo', JSON.stringify(res.user_info));
                this.setUserInfo(res.user_info);
                this.setToken(res.ak);
                this.$router.push('/suser');
              })
              .catch(() => {
                this.$message.error('账号密码错误');
              });
          }
        });
      },
    },
  };
</script>

<style lang="less" scoped>
  .login {
    background: #f0f0f0;
    .login-box {
      padding: 20px 30px;
      background: #fff;
      border-radius: 0.3rem;
      .head {
        font-size: 20px;
        margin-bottom: 20px;
      }
    }
  }
</style>
